// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()
const MAX_LIMIT = 50

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  const countResult = await db.collection('invoices').where({
    _openid: wxContext.OPENID
  }).count()
  const total = countResult.total
  const batchTimes = Math.ceil(total / MAX_LIMIT)
  const invoices = []
  //
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('invoices').where({
      _openid: wxContext.OPENID
    }).orderBy('createDate', 'desc').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    invoices.push(promise)
  }
  if (invoices.length == 0) {
    return {
      data: [],
      errMsg: 'no data found!'
    }
  }
  // 等待所有
  return (await Promise.all(invoices)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
}